<template>
  <div class="employee-list">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>员工管理</h2>
    </div>

    <!-- 查询条件 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="员工姓名">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入员工姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="员工类型">
          <el-select
            v-model="searchForm.type"
            placeholder="请选择员工类型"
            clearable
            style="width: 150px"
          >
            <el-option label="全职" value="FULL_TIME" />
            <el-option label="兼职" value="PART_TIME" />
            <el-option label="临时工" value="TEMPORARY" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="在职" value="ACTIVE" />
            <el-option label="离职" value="INACTIVE" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="table-toolbar">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增员工
      </el-button>
      <el-button
        type="danger"
        :disabled="selectedIds.length === 0"
        @click="handleBatchDelete"
      >
        <el-icon><Delete /></el-icon>
        批量删除
      </el-button>
    </div>

    <!-- 员工表格 -->
    <el-table
      v-loading="loading"
      :data="employeeList"
      @selection-change="handleSelectionChange"
      stripe
      border
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="phone" label="电话" width="130" />
      <el-table-column prop="email" label="邮箱" width="180" />
      <el-table-column prop="employeeType" label="员工类型" width="100">
        <template #default="{ row }">
          <el-tag :type="getTypeTagType(row.employeeType)">
            {{ getTypeText(row.employeeType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="priority" label="优先级" width="80" />
      <el-table-column prop="status" label="状态" width="80">
        <template #default="{ row }">
          <el-tag :type="row.status === 'ACTIVE' ? 'success' : 'danger'">
            {{ row.status === 'ACTIVE' ? '在职' : '离职' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="hireDate" label="入职日期" width="120" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 员工表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="employeeFormRef"
        :model="employeeForm"
        :rules="employeeRules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="employeeForm.name" placeholder="请输入员工姓名" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="employeeForm.phone" placeholder="请输入电话号码" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="employeeForm.email" placeholder="请输入邮箱地址" />
        </el-form-item>
        <el-form-item label="员工类型" prop="type">
          <el-select v-model="employeeForm.type" placeholder="请选择员工类型">
            <el-option label="全职" value="FULL_TIME" />
            <el-option label="兼职" value="PART_TIME" />
            <el-option label="临时工" value="TEMPORARY" />
          </el-select>
        </el-form-item>
        <el-form-item label="薪资等级" prop="salaryLevel">
          <el-input-number
            v-model="employeeForm.salaryLevel"
            :min="1"
            :max="10"
            placeholder="请输入薪资等级(1-10)"
          />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-input-number
            v-model="employeeForm.priority"
            :min="1"
            :max="10"
            placeholder="请输入优先级(1-10)"
          />
        </el-form-item>
        <el-form-item label="入职日期" prop="hireDate">
          <el-date-picker
            v-model="employeeForm.hireDate"
            type="date"
            placeholder="请选择入职日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="employeeForm.status">
            <el-radio value="ACTIVE">在职</el-radio>
            <el-radio value="INACTIVE">离职</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import {
  getEmployeeList,
  createEmployee,
  updateEmployee,
  deleteEmployee,
  batchDeleteEmployees
} from '@/api/employee'

// 响应式数据
const loading = ref(false)
const employeeList = ref([])
const selectedIds = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const employeeFormRef = ref()

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  status: ''
})

// 分页信息
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 员工表单
const employeeForm = reactive({
  id: null,
  name: '',
  phone: '',
  email: '',
  type: '',
  salaryLevel: 1,
  priority: 1,
  hireDate: '',
  status: 'ACTIVE'
})

// 表单验证规则
const employeeRules = {
  name: [
    { required: true, message: '请输入员工姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入电话号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择员工类型', trigger: 'change' }
  ],
  salaryLevel: [
    { required: true, message: '请输入薪资等级', trigger: 'blur' }
  ],
  priority: [
    { required: true, message: '请输入优先级', trigger: 'blur' }
  ],
  hireDate: [
    { required: true, message: '请选择入职日期', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 获取员工列表
const fetchEmployeeList = async () => {
  loading.value = true
  try {
    const mapTypeToInt = (t) => {
      switch (t) {
        case 'FULL_TIME':
          return 1
        case 'PART_TIME':
          return 2
        case 'TEMPORARY':
          return 3
        default:
          return undefined
      }
    }
    const mapStatusToInt = (s) => (s === 'ACTIVE' ? 1 : s === 'INACTIVE' ? 0 : undefined)
    const params = {
      page: pagination.page - 1, // 后端从0开始
      size: pagination.size,
      name: searchForm.name || undefined,
      employeeType: mapTypeToInt(searchForm.type),
      status: mapStatusToInt(searchForm.status)
    }
    const data = await getEmployeeList(params)
    // 兼容后端当前返回 Result<List<Employee>> 的数据结构
    if (Array.isArray(data)) {
      employeeList.value = data
      pagination.total = data.length || 0
    } else {
      // 若后端改为分页结构 Result<Page<Employee>>，也兼容处理
      employeeList.value = (data && data.content) || []
      pagination.total = (data && data.totalElements) || (employeeList.value?.length || 0)
    }
  } catch (error) {
    ElMessage.error('获取员工列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchEmployeeList()
}

// 重置搜索条件
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    type: '',
    status: ''
  })
  pagination.page = 1
  fetchEmployeeList()
}

// 新增员工
const handleAdd = () => {
  dialogTitle.value = '新增员工'
  resetEmployeeForm()
  dialogVisible.value = true
}

// 编辑员工
const handleEdit = (row) => {
  dialogTitle.value = '编辑员工'
  const toTypeString = (t) => {
    switch (t) {
      case 1:
        return 'FULL_TIME'
      case 2:
        return 'PART_TIME'
      case 3:
        return 'TEMPORARY'
      default:
        return ''
    }
  }
  const toStatusString = (s) => (s === 1 ? 'ACTIVE' : 'INACTIVE')
  const toDate = (dt) => {
    if (!dt) return ''
    try {
      const d = new Date(dt)
      const y = d.getFullYear()
      const m = `${d.getMonth() + 1}`.padStart(2, '0')
      const dd = `${d.getDate()}`.padStart(2, '0')
      return `${y}-${m}-${dd}`
    } catch (e) {
      return ''
    }
  }
  Object.assign(employeeForm, {
    id: row.id,
    name: row.name,
    phone: row.phone,
    email: row.email,
    type: toTypeString(row.employeeType),
    salaryLevel: row.salaryLevel ?? 1,
    priority: employeeForm.priority,
    hireDate: toDate(row.hireDate),
    status: toStatusString(row.status)
  })
  dialogVisible.value = true
}

// 删除员工
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除员工 "${row.name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await deleteEmployee(row.id)
    ElMessage.success('删除成功')
    fetchEmployeeList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedIds.value.length} 个员工吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await batchDeleteEmployees(selectedIds.value)
    ElMessage.success('批量删除成功')
    selectedIds.value = []
    fetchEmployeeList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  fetchEmployeeList()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.page = page
  fetchEmployeeList()
}

// 提交表单
const handleSubmit = async () => {
  try {
    await employeeFormRef.value.validate()
    const mapTypeToInt = (t) => {
      switch (t) {
        case 'FULL_TIME':
          return 1
        case 'PART_TIME':
          return 2
        case 'TEMPORARY':
          return 3
        default:
          return null
      }
    }
    const mapStatusToInt = (s) => (s === 'ACTIVE' ? 1 : 0)
    const formatHireDate = (d) => (d ? `${d}T00:00:00` : null)
    const payload = {
      name: employeeForm.name,
      phone: employeeForm.phone,
      email: employeeForm.email,
      salaryLevel: employeeForm.salaryLevel,
      employeeType: mapTypeToInt(employeeForm.type),
      status: mapStatusToInt(employeeForm.status),
      hireDate: formatHireDate(employeeForm.hireDate)
    }
    if (employeeForm.id) {
      await updateEmployee(employeeForm.id, payload)
      ElMessage.success('更新成功')
    } else {
      await createEmployee(payload)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    fetchEmployeeList()
  } catch (error) {
    if (error.message) {
      ElMessage.error('操作失败')
    }
  }
}

// 对话框关闭
const handleDialogClose = () => {
  employeeFormRef.value?.resetFields()
  resetEmployeeForm()
}

// 重置员工表单
const resetEmployeeForm = () => {
  Object.assign(employeeForm, {
    id: null,
    name: '',
    phone: '',
    email: '',
    type: '',
    salaryLevel: 1,
    priority: 1,
    hireDate: '',
    status: 'ACTIVE'
  })
}

// 获取员工类型标签类型
const getTypeTagType = (type) => {
  switch (type) {
    case 1:
      return 'success'
    case 2:
      return 'warning'
    case 3:
      return 'info'
    default:
      return 'info'
  }
}

// 获取员工类型文本
const getTypeText = (type) => {
  switch (type) {
    case 1:
      return '全职'
    case 2:
      return '兼职'
    case 3:
      return '临时工'
    default:
      return ''
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchEmployeeList()
})
</script>

<style scoped>
.employee-list {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-form {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-toolbar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.el-table {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>